package com.dikang.yygh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dikang.yygh.listener.DictListener;
import com.dikang.yygh.mapper.DictMapper;
import com.dikang.yygh.model.cmn.Dict;
import com.dikang.yygh.service.DictService;
import com.dikang.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * * @Cacheable value 缓存名，必填，它指定了你的缓存存放在哪块命名空间 keyGenerator是自定义key名称的规则
     *
     * @param id
     * @return
     */
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", id));
        for (Dict dict : dictList) {
            if (isExistChildData(dict.getId())) {
                dict.setHasChildren(isExistChildData(dict.getId()));
            }
        }
        return dictList;
    }

    /**
     * Excel字典数据导出
     *
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里是UrlEncoder的encoding防止中文乱码
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                dictEeVoList.add(dictEeVo);

            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //allEntries = true: 方法调用后清空所有缓存
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public String findDictName(String dictCode, String value) {
        System.out.println(dictCode);
        System.out.println(value);
        if (!StringUtils.isEmpty(dictCode)) {

            // 根据dictCode查询出id
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
            QueryWrapper queryWrapper= new QueryWrapper<Dict>();
            queryWrapper.eq("parent_id",dict.getId());
            queryWrapper.eq("value",value);

            Dict targetDict = baseMapper.selectOne(queryWrapper);
            return targetDict.getName();
 
        } else {
            //直接根据value查询
            Dict targetDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            System.out.println(targetDict);
            return targetDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        if (dict !=null){
            return  this.findChildData(dict.getId());
        }else {
            return null;
        }

    }

    private boolean isExistChildData(Long id) {
        Integer count = baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id));
        return count > 0;

    }
}
